<template>
  <page-view class="food-detail">
    <page-header title="菜品详情" :show-back="true"></page-header>
    <div class="content-box" v-if="foodDetail">
      <van-skeleton title avatar :row="5" :loading="isLoading">
        <!-- 图片展示 -->
        <div class="food-img-box">
          <img
            v-lazy="foodDetail.food_img ? foodDetail.food_img[0] : ''"
            @click.stop="showThisImage"
          />
        </div>
        <!-- 详情展示 -->
        <ul class="food-desc">
          <li><span>菜品名称：</span>{{ foodDetail.food_name }}</li>
          <li><span>菜品价格：</span>{{ foodDetail.price }}</li>
          <li><span>菜品销量：</span>{{ foodDetail.sales }}</li>
          <li class="food-intro">
            {{ foodDetail.food_desc }}
          </li>
        </ul>
        <!-- 评论 -->
        <div class="comment-list">
          <h3 class="text-primary">最新评论</h3>
          <van-list
            :loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <comment-item
              v-for="(item, index) in commentList"
              :key="index"
              :c_item="item"
            ></comment-item>
          </van-list>
        </div>
        <!-- 购物车bar -->
        <van-action-bar>
          <van-action-bar-icon icon="chat-o" text="客服" dot />
          <van-action-bar-icon
            icon="cart-o"
            text="购物车"
            :badge="shopCartBarData.totalCount"
            @click="$router.push({ name: 'shopCart' })"
          />
          <van-action-bar-button
            type="warning"
            text="加入购物车"
            @click="addToShopCart"
            :loading="shopCartButtonLoading"
          />
          <van-action-bar-button type="danger" text="立即购买" @click="buy" />
        </van-action-bar>
      </van-skeleton>
    </div>
  </page-view>
</template>

<script setup>
import CommentItem from "../components/CommentItem.vue";
import { reactive, toRefs, inject, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showImagePreview, showToast, showNotify } from "vant";
import { useStore } from "vuex";
const route = useRoute();
const BaseURL = inject("BaseURL");
import api from "../utils/api";
const info = reactive({
  foodDetail: {},
  isLoading: false,
});
const getFoodDetailById = async (id) => {
  info.isLoading = true;
  let result = await api.foodInfo.findById(id);
  console.log(result);
  result[0].food_img = result[0].food_img.split(",");
  for (const index in result[0].food_img) {
    result[0].food_img[index] = BaseURL + result[0].food_img[index];
  }
  info.foodDetail = result[0];
  info.isLoading = false;
};
getFoodDetailById(route.params.id);

const { foodDetail, isLoading } = toRefs(info);

const showThisImage = (e) => {
  showImagePreview(info.foodDetail.food_img);
};

const loading = ref(false);
const finished = ref(false);
const pageIndex = ref(1);
const commentList = reactive([]);
const totalPage = ref(0);
const getComment = async (e) => {
  let result = await api.commentInfo.getCommentInfoByFid(
    route.params.id,
    pageIndex.value
  );
  // console.log(result);
  totalPage.value = result.totalPage;
  result.list.forEach((item) => {
    item.user_photo = BaseURL + item.user_photo;
    commentList.push(item);
  });
  loading.value = false;
  finished.value = pageIndex.value >= totalPage.value;
};
getComment();

const onLoad = () => {
  if (pageIndex.value < totalPage.value) {
    pageIndex.value++;
    getComment();
  }
};

// 购物车
const store = useStore();
const router = useRouter();
const shopCartButtonLoading = ref(false);
const shopCartBarData = reactive({
  totalPrice: 0,
  totalCount: 0,
});

const getMyShopCartTotalInfo = async () => {
  let userInfo = store.state.userInfo;
  if (userInfo) {
    let result = await api.shopCartInfo.findAllByUid();
    shopCartBarData.totalCount = result[0].totalCount;
    shopCartBarData.totalPrice = result[0].price;
  } else {
    showToast("请先登录");
    router.push({ name: "login" });
  }
};
getMyShopCartTotalInfo();

const addToShopCart = async () => {
  shopCartButtonLoading.value = true;
  let userInfo = store.state.userInfo;
  if (userInfo) {
    let result = await api.shopCartInfo.add(route.params.id, 1);
    showNotify({
      type: "success",
      message: "添加到购物车成功",
      position: "bottom",
      duration: 1000,
      onClose: function () {
        shopCartButtonLoading.value = false;
      },
    });
    getMyShopCartTotalInfo();
  }
};

const buy = async () => {
  info.foodDetail.count = 1;
  info.foodDetail.fid = info.foodDetail.id;
  let arr = [];
  arr.push(info.foodDetail);
  router.push({
    name: "checkOrder",
    query: { goods: JSON.stringify(arr), totalMoney: arr[0].price },
  });
};
</script>

<style lang="scss" scoped>
.food-detail {
  @include flexbox(column);
  .content-box {
    flex: 1;
    overflow: auto;
    padding-bottom: 50px;
    .food-img-box {
      height: 250px;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .food-desc {
      box-sizing: border-box;
      padding: 5px;
      border-bottom: 1px solid lightgray;
      li {
        line-height: 1.8;
        > span {
          font-weight: bold;
        }
        &.food-intro {
          text-indent: 2em;
        }
      }
    }
  }
}
</style>